package com.xhj.myframe.myAQS;

import org.testng.annotations.Test;

import java.util.concurrent.locks.ReentrantLock;

import static java.lang.System.currentTimeMillis;
/** @author haijianxia pure_xhj@163.com @Date 2021-08-24 @Time 18:02 */
public class ReentrantLockDemo {

  //	javap -c a_ReentryLockDemo.class

  static ReentrantLock lock = new ReentrantLock();

  public static void main(String[] args) {
    Object sysLock = new Object();
    synchronized (sysLock) {
      System.out.println("外层===");
      synchronized (sysLock) {
        System.out.println("内层===");
      }
    }
    System.out.println("==================================================");
    doOut();
    System.out.println("==========================测试lock==========================");
    new Thread(
            () -> {
              lock.lock();
              try {
                System.out.println(Thread.currentThread().getName() + " come in...");
              } catch (Exception e) {
                e.printStackTrace();
              } finally {
                lock.unlock();
              }
            },
            "AAA")
        .start();
    new Thread(
            () -> {
              lock.lock();
              //      lock.unlock();
              try {
                System.out.println(Thread.currentThread().getName() + " come in...");
              } catch (Exception e) {
                e.printStackTrace();
              } finally {
                lock.unlock();
              }
            },
            "BBB")
        .start();
  }

  @Test
  public void test() {
    System.out.println("=============test==============");
    System.out.println("");
    long time = currentTimeMillis();

    System.out.println("==========================重入lock==========================");
    new Thread(
            () -> {
              lock.lock();
              System.out.println(Thread.currentThread().getName() + " come outer...");
              try {
                lock.unlock();
                System.out.println(Thread.currentThread().getName() + " come inner...");
                try {
                } catch (Exception e) {
                  e.printStackTrace();
                } finally {
                  lock.lock();
                }
              } catch (Exception e) {
                e.printStackTrace();
              } finally {
                lock.unlock();
              }
            },
            "QQQ")
        .start();

    long time1 = currentTimeMillis() - time;
    System.out.println("\n耗时 =  " + time1 + "ms");
    System.out.println("=================================");
  }

  static synchronized void doOut() {
    System.out.println("doOut");
    doInner();
  }

  static synchronized void doInner() {
    System.out.println("doInner");
  }
}
